package com.brsya.autonat.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;

import com.brsya.autonat.MyApplication;
import com.brsya.autonat.R;
import com.brsya.autonat.constant.Constant;
import com.brsya.autonat.service.MyService;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tvChangeConfig;
    private TextView btnOpenChangeConfig;
    private SwitchCompat swOpenAuto;
    private TextView tvBluetoothInfo;
    private SwitchCompat swOpenSignal;

    private ActivityResultLauncher<Intent> intentActivityResultLauncher;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        initListener();


        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
                , new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        // TODO: 2023/2/11 保存
                        if (result.getResultCode() == RESULT_OK) {
                            if (result.getData() == null) {
                                return;
                            }
                            Intent intent = result.getData();
                            String name = intent.getStringExtra(Constant.KEY_BLUETOOTH_NAME);
                            String address = intent.getStringExtra(Constant.KEY_BLUETOOTH_ADDRESS);
                            MyApplication.putString(Constant.KEY_BLUETOOTH_NAME, name);
                            MyApplication.putString(Constant.KEY_BLUETOOTH_ADDRESS, address);
                            MyApplication.putBoolean(Constant.KEY_IS_OPEN_AUTO_NAT, true);
                        } else {
                            MyApplication.putBoolean(Constant.KEY_IS_OPEN_AUTO_NAT, false);
                        }
                        refreshConfig();
                    }
                });

        refreshConfig(false);

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (applySystemConfigChange()) {
            tvChangeConfig.setText("已开启");
            tvChangeConfig.setVisibility(View.VISIBLE);
            btnOpenChangeConfig.setVisibility(View.GONE);
        } else {
            tvChangeConfig.setVisibility(View.GONE);
            btnOpenChangeConfig.setVisibility(View.VISIBLE);
        }
    }

    private void initView() {
        tvChangeConfig = findViewById(R.id.tv_change_config);
        btnOpenChangeConfig = findViewById(R.id.btn_open_change_config);
        swOpenAuto = findViewById(R.id.sw_open_auto);
        tvBluetoothInfo = findViewById(R.id.tv_bluetooth_info);
        swOpenSignal = (SwitchCompat) findViewById(R.id.sw_open_signal);
    }

    private void initListener() {
        btnOpenChangeConfig.setOnClickListener(this);
        tvBluetoothInfo.setOnClickListener(this);

        swOpenAuto.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            stopService(new Intent(MainActivity.this, MyService.class));
                if (isChecked) {
                    MyApplication.putBoolean(Constant.KEY_IS_OPEN_AUTO_NAT, true);
                    String address = MyApplication.getString(Constant.KEY_BLUETOOTH_ADDRESS);
                    if (address == null || address.trim().length() == 0) {
                        getBluetoothList();
                    }
                    startService(new Intent(MainActivity.this, MyService.class));
                } else {
                    MyApplication.putBoolean(Constant.KEY_IS_OPEN_AUTO_NAT, false);
                    // 关闭显示信号开关，判断是否打开另一开关
                    if (MyApplication.getBoolean(Constant.KEY_IS_OPEN_SIGNAL)) {
                        // 打开自动打开热点开关，不关闭服务
                        startService(new Intent(MainActivity.this, MyService.class));
                    }
                }

                refreshConfig(false);
            }
        });
        swOpenSignal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                stopService(new Intent(MainActivity.this, MyService.class));
                MyApplication.putBoolean(Constant.KEY_IS_OPEN_SIGNAL, isChecked);
                if (isChecked) {
                    // 打开显示信号开关，开启服务
                    startService(new Intent(MainActivity.this, MyService.class));
                }else{
                    // 关闭显示信号开关，判断是否打开另一开关
                    if (MyApplication.getBoolean(Constant.KEY_IS_OPEN_AUTO_NAT)) {
                        // 打开自动打开热点开关，不关闭服务
                        startService(new Intent(MainActivity.this, MyService.class));
                    }
                }
            }
        });

        if (MyApplication.getBoolean(Constant.KEY_IS_OPEN_SIGNAL)) {
            swOpenSignal.setChecked(true);
        }
    }


    public boolean applySystemConfigChange() {
        if (!Settings.System.canWrite(MainActivity.this)) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
                    Uri.parse("package:" + getPackageName()));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivityForResult(intent, 200);
            return false;
        } else {
            // 如果有权限做些什么
            return true;
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_open_change_config) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS,
                    Uri.parse("package:" + getPackageName()));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        } else if (id == R.id.tv_bluetooth_info) {
            getBluetoothList();
            swOpenAuto.setChecked(false);
        }
    }


    private void getBluetoothList() {
        Intent intent = new Intent(this, SelectBluetoothActivity.class);
        intentActivityResultLauncher.launch(intent);
    }

    private void refreshConfig() {
        refreshConfig(true);
    }

    private void refreshConfig(boolean isChangeSwitch) {
        // 设置已选蓝牙信息
        String address = MyApplication.getString(Constant.KEY_BLUETOOTH_ADDRESS);
        if (address != null && address.trim().length() > 0) {
            String name = MyApplication.getString(Constant.KEY_BLUETOOTH_NAME);
            String selectBluetooth = String.format("%s(%s)"
                    , name
                    , address);
            tvBluetoothInfo.setText(selectBluetooth);
        }
        if (MyApplication.getBoolean(Constant.KEY_IS_OPEN_AUTO_NAT)) {
            // 打开开关
            if (isChangeSwitch) {
                swOpenAuto.setChecked(true);
            }
//            startService(new Intent(MainActivity.this, MyService.class));
        } else {
            // 关闭开关
            if (isChangeSwitch) {
                swOpenAuto.setChecked(false);
            }
//            stopService(new Intent(MainActivity.this, MyService.class));
        }
    }
}